package cn.yangyumanage.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import cn.yangyumanage.R;
import cn.yangyumanage.adapter.FilmManageRvAdapter;
import cn.yangyumanage.application.DataApplication;
import cn.yangyumanage.bean.Film;
import cn.yangyumanage.bean.Page;
import cn.yangyumanage.callback.DataCallBack;
import cn.yangyumanage.http.HttpClient;
import cn.yangyumanage.model.FilmManageHttpModel;
import cn.yangyumanage.util.ToastUtil;
import cn.yangyumanage.util.ViewUtil;

public class FilmManageFragment extends Fragment implements View.OnClickListener, TextView.OnEditorActionListener , Serializable {
    private final FilmManageHttpModel model = new FilmManageHttpModel();
    private Activity activity;
    private View view;
    private RecyclerView rv_manage;
    private SmartRefreshLayout srl_manage;
    private List<Film> filmList = new ArrayList<>();
    private FilmManageRvAdapter adapter;
    private int pageNum = 1;
    private int queryPageNum = 1;
    private int pageSize = 10;
    private EditText et_search;
    private TextView tv_search;

    public FilmManageFragment() {
    }

    public FilmManageFragment(Activity activity) {
        this.activity = activity;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_film_manage, container, false);
        initView();
        initData();
        return view;
    }

    @Override
    public void onResume() {
        if (!DataApplication.dataFlag){
            rv_manage.scrollToPosition(0);
            srl_manage.autoRefresh();
            DataApplication.dataFlag=true;
        }
        super.onResume();
    }

    private void initData(){
        initAdapter();
        getPage(pageNum, pageSize);
    }

    private void initView() {
        rv_manage = view.findViewById(R.id.rv_manage);
        srl_manage = view.findViewById(R.id.srl_manage);
        srl_manage.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                ViewUtil.hideOneInputMethod(activity, et_search);
                String queryContent = et_search.getText().toString();
                if (queryContent.equals("")) {
                    filmList.clear();
                    pageNum = 1;
                    getPage(pageNum, pageSize);
                } else {
                    filmList.clear();
                    queryPageNum = 1;
                    fuzzyQuery(queryPageNum, pageSize, queryContent);
                }
            }
        });
        srl_manage.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                String queryContent = et_search.getText().toString();
                if (queryContent.equals("")) {
                    pageNum++;
                    getPage(pageNum, pageSize);
                } else {
                    queryPageNum++;
                    fuzzyQuery(queryPageNum, pageSize, queryContent);
                }
            }
        });
        et_search = view.findViewById(R.id.et_search);
        et_search.setOnEditorActionListener(this);
        tv_search = view.findViewById(R.id.tv_search);
        tv_search.setOnClickListener(this);
    }

    private void initAdapter() {
        adapter = new FilmManageRvAdapter(activity, filmList);
        rv_manage.setAdapter(adapter);
        rv_manage.setLayoutManager(new LinearLayoutManager(activity));
    }

    //影片分页查询
    private void getPage(int currentPage, int pageSize) {
        model.getPage(currentPage, pageSize, new DataCallBack() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void getData(Object data) {
                Page<Film> page = (Page) data;
                List<Film> records = page.getRecords();
                filmList.addAll(records);
                HttpClient.handler.post(() -> {
                    if (records.size() == 0) {
                        ToastUtil.show(activity, "没有更多数据了");
                        pageNum--;
                    }
                    srl_manage.finishLoadMore();
                    srl_manage.finishRefresh();
                    adapter.notifyDataSetChanged();
                });
            }
        });
    }

    //模糊查询
    private void fuzzyQuery(int currentPage, int pageSize, String queryContent) {
        model.fuzzyQuery(currentPage, pageSize, queryContent, new DataCallBack() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void getData(Object data) {
                Page<Film> page = (Page) data;
                List<Film> records = page.getRecords();
                filmList.addAll(records);
                HttpClient.handler.post(() -> {
                    if (records.size() == 0) {
                        ToastUtil.show(activity, "没有更多数据了");
                        queryPageNum--;
                    }
                    srl_manage.finishLoadMore();
                    srl_manage.finishRefresh();
                    adapter.notifyDataSetChanged();
                });
            }
        });
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_search:
                String queryContent = et_search.getText().toString();
                ViewUtil.hideOneInputMethod(activity, et_search);
                if (queryContent.equals("")) {
                    et_search.clearFocus();
                    break;
                }
                filmList.clear();
                queryPageNum = 1;
                fuzzyQuery(queryPageNum, pageSize, queryContent);
                et_search.clearFocus();
                break;
        }
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        //监听搜索键
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            String queryContent = et_search.getText().toString();
            ViewUtil.hideOneInputMethod(activity, et_search);
            if (queryContent.equals("")) {
                et_search.clearFocus();
                return false;
            }
            filmList.clear();
            queryPageNum = 1;
            fuzzyQuery(queryPageNum, pageSize, queryContent);
            et_search.clearFocus();
            return true;
        }
        return false;
    }
}